package com.zlc.platform.service.impl;

import com.github.pagehelper.PageHelper;
import com.zlc.common.common.entity.PageVo;
import com.zlc.common.common.exception.BusinessException;
import com.zlc.common.common.service.AutowiredService;
import com.zlc.common.core.position.model.entity.MayanPlatPosition;
import com.zlc.common.core.position.model.vo.MayanPlatPositionVo;
import com.zlc.common.core.role.model.vo.MayanPlatRoleVo;
import com.zlc.common.util.AssertUtils;
import com.zlc.common.model.position.PositionPageRequest;
import com.zlc.platform.service.PositionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class PositionServiceImpl  extends AutowiredService implements PositionService {


    @Override
    public PageVo<MayanPlatPositionVo> queryList(PositionPageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPageNum(),pageRequest.getPageSize());
        List<MayanPlatPositionVo> list = mayanPlatPositionMapper.queryList(pageRequest);
        return PageVo.page(list);
    }

    @Override
    public void addPosition(MayanPlatPositionVo positionVo) {
        String positionCode = positionVo.getPositionCode();
        checkParam(positionVo);

        MayanPlatPositionVo oldPosition = mayanPlatPositionService.getByPositionCode(positionCode);
        if(!ObjectUtils.isEmpty(oldPosition)){
            throw new BusinessException("岗位code已存在");
        }
        mayanPlatPositionService.saveVo(positionVo);
    }

    @Override
    public void updatePosition(MayanPlatPositionVo positionVo) {
        String positionCode = positionVo.getPositionCode();
        checkParam(positionVo);

        MayanPlatPositionVo oldPosition = mayanPlatPositionService.getByPositionCode(positionCode);
        if(!ObjectUtils.isEmpty(oldPosition) && !oldPosition.getId().equals(positionVo.getId())){
            throw new BusinessException("岗位code已存在");
        }
        mayanPlatPositionService.saveVo(positionVo);
    }

    private void checkParam(MayanPlatPositionVo positionVo) {
        String roleCode = positionVo.getRoleCode();
        String positionCode = positionVo.getPositionCode();
        String positionName = positionVo.getPositionName();
        AssertUtils.isTrue(!ObjectUtils.isEmpty(roleCode), "角色不可为空");
        AssertUtils.isTrue(!ObjectUtils.isEmpty(positionCode), "岗位code不可为空");
        AssertUtils.isTrue(!ObjectUtils.isEmpty(positionName), "岗位名称不可为空");

        MayanPlatRoleVo roleVo = mayanPlatRoleService.getByRoleCode(roleCode);
        AssertUtils.isTrue(!ObjectUtils.isEmpty(roleVo),"角色"+roleCode+"不存在");
    }

    @Override
    public MayanPlatPosition get(String id) {
        return mayanPlatPositionService.getById(id);
    }
}
